package com.situ.mall.recommend;

import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.pojo.entity.Product;
import com.situ.mall.pojo.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ProductRecommendationService {

    @Autowired
    private ProductSimilarityService productSimilarityService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;

    // 根据用户最新的订单推荐商品
    public List<ProductVO> recommendProductsForUser(int userId, int numberOfRecommendations) {
        // 获取用户最新的订单中的商品ID
        Integer lastOrderedProductId = orderMapper.getLastOrderedProductIdByUser(userId);
        if (lastOrderedProductId == null) {
            return Collections.emptyList();
        }

        // 获取所有商品间的相似度
        Map<Integer, Map<Integer, Double>> similarityMatrix = productSimilarityService.calculateAllSimilarities();

        // 获取与最新订单商品相似度最高的商品
        Map<Integer, Double> productSimilarities = similarityMatrix.getOrDefault(lastOrderedProductId, new HashMap<>());

        // 根据相似度排序并选择前N个
        List<Map.Entry<Integer, Double>> sortedSimilarProducts = new ArrayList<>(productSimilarities.entrySet());
        sortedSimilarProducts.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

        List<ProductVO> recommendedProducts = new ArrayList<>();
        int count = 0;
        for (Map.Entry<Integer, Double> entry : sortedSimilarProducts) {
            if (count >= numberOfRecommendations) {
                break;
            }
            // 获取商品详细信息
            ProductVO product = productMapper.selectById(entry.getKey());
            if (product != null && product.getStatus() == 1 && product.getIsDeleted() == 0) { // 确保商品在售且未删除
                recommendedProducts.add(product);
                count++;
            }
        }

        return recommendedProducts;
    }
}